package com.xiaotao.consumer;

import com.rabbitmq.client.Channel;

import com.xiaotao.entity.Orders;
import com.xiaotao.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

import static com.xiaotao.config.RabbitConfig.QUEUE_CHECK_ORDER_STATUS;

@Component
@Slf4j
public class CheckOrderConsumer {
    @Resource
    private
    OrdersMapper ordersMapper;

    /**
     * 延迟队列监听
     */
    @RabbitListener(queues =QUEUE_CHECK_ORDER_STATUS)
    public void consume(String id, Channel channel, Message message)
    {
        try
        {
            log.info("延迟队列收到订单消息: {}", id);
            Orders orders = ordersMapper.selectByPrimaryKey(id);
            if (orders != null && orders.getStatus() == 0) {
//                ordersMapper.updateStatus(orderNo, 2); // 取消订单
                log.info("订单 {} 超时未支付，已取消", id);
            }
            else
            {
                log.info("订单 {} 已支付或不存在，无需取消", id);
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        }
        catch
        (Exception e) {
            log.error("处理订单 {} 异常", id,e);
            try {
                // 重回队列或死信
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }
            catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
